package com.cheng.im.gateway.handler;

import com.cheng.im.common.bean.msg.ProtoMsg;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.cheng.im.common.cocurrent.CallbackTask;
import com.cheng.im.common.cocurrent.CallbackTaskScheduler;
import com.cheng.im.gateway.processer.LoginProcesser;
import com.cheng.im.gateway.session.LocalSession;
import com.cheng.im.gateway.session.manager.SessionManger;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Cheng
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class LoginRequestHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private LoginProcesser loginProcesser;
    @Resource
    private SensitiveWordHandler sensitiveWordHandler;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        log.info("执行登录处理器");

        // 判断消息类型
        if (!(msg instanceof ProtoMsgV1.Message))
        {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsgV1.Message pkg = (ProtoMsgV1.Message) msg;

        // 判断请求类型
        ProtoMsgV1.HeadType headType = pkg.getType();
        if (!headType.equals(ProtoMsgV1.HeadType.LOGIN_REQUEST))
        {
            super.channelRead(ctx, msg);
            return;
        }

        // log.info("登录消息：{}", pkg);

        // 初始化本地会话
        LocalSession localSession = new LocalSession(ctx.channel());

        CallbackTaskScheduler.add(
                new CallbackTask<Boolean>()
                {
                    @Override
                    public Boolean execute() throws Exception
                    {
                        return loginProcesser.action(localSession, pkg);
                    }
                    // 异步任务返回
                    @Override
                    public void onBack(Boolean r)
                    {
                        if (r)
                        {
                            log.info("登录成功: {}", localSession.getUser());
                            ctx.pipeline().addAfter("login", "heartBeat",new HeartBeatServerHandler());
                            ctx.pipeline().remove("login");
                        } else
                        {
                            log.info("登录失败:" + localSession.getUser());
                        }

                    }
                    // 异步任务异常
                    @Override
                    public void onException(Throwable t)
                    {
                        t.printStackTrace();
                        log.info("登录失败:" + localSession.getUser());
                        SessionManger.inst().closeSession(ctx);
                    }
                }
        );
    }
}
